package com.huaxin.hxmodulesystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huaxin.hxjwt.common.JwtHeaderUtils;
import com.huaxin.hxmodulesystem.common.CaptchaUtil;
import com.huaxin.hxmodulesystem.dto.ResponseCode;
import com.huaxin.hxmodulesystem.dto.ResponseResult;
import com.huaxin.hxmodulesystem.dto.request.LoginByPhoneAndUserNameAndPasswordReqDTO;
import com.huaxin.hxmodulesystem.dto.request.RegisterUserReqDTO;
import com.huaxin.hxmodulesystem.dto.request.UpdateUserInfoReqDTO;
import com.huaxin.hxmodulesystem.dto.request.WxUserLoginReqDTO;
import com.huaxin.hxmodulesystem.dto.response.LoginByPhoneAndUserNameAndPasswordRespDTO;
import com.huaxin.hxmodulesystem.dto.response.WxLoginRespDTO;
import com.huaxin.hxmodulesystem.models.User;
import com.huaxin.hxmodulesystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;


@Tag(name = "用户模块")
@RestController
@RequestMapping("/v1/sys/users")
@RequiredArgsConstructor
public class UserController {
    private final CaptchaUtil captchaUtil;
    private final UserService usersService;

    @Operation(summary = "微信登录", description = "微信登录")
    @PostMapping("/weChatLogin")
    public ResponseResult<WxLoginRespDTO> weChatLogin(@RequestBody WxUserLoginReqDTO in) {
        try {
            // 获取请求参数
            return usersService.loginOrRegister(in);
        } catch (Exception e) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "登录失败，请稍后重试！", null);
        }
    }

    //更新用户信息
    @Operation(summary = "更新用户信息", description = "更新用户信息", security = @SecurityRequirement(name = "JWT Authentication"))
    @PostMapping("/updateUserInfo")
    public ResponseResult<String> updateUserInfo(@RequestBody UpdateUserInfoReqDTO in) {
        if (StringUtils.isBlank(in.getUserId())) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "用户未登录！", null);
        }
        if (StringUtils.isBlank(in.getPhone())) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "手机号码不能为空！", null);
        }
        if (StringUtils.isBlank(in.getNickname())) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "昵称不能为空！", null);
        }
        if (in.getUserType() == null || in.getUserType() <= 0) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "用户类型不能为空！", null);
        }
        return usersService.updateUserInfo(in);
    }

    //根据用户Id查询用户信息
    @Operation(summary = "根据用户openId查询用户信息", description = "根据用户openId查询用户信息", security = @SecurityRequirement(name = "JWT Authentication"))
    @GetMapping("/getUserInfoByOpenId")
    public ResponseResult<User> getUserInfoByOpenId(HttpServletRequest request) {
        String userId = JwtHeaderUtils.getUserId(request);
        String openId = JwtHeaderUtils.getOpenId(request);
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(openId)) {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "用户未登录！", null);
        }
        return ResponseResult.ok(usersService.getUserInfoById(userId));
    }


    //用户注册
    @Operation(summary = "用户注册", description = "用户注册")
    @PostMapping("/registerUser")
    public ResponseResult<String> registerUser(@RequestBody RegisterUserReqDTO in) {
        return usersService.registerUser(in);
    }

    //用户用手机号或用户名码加密码进行登录
    @Operation(summary = "账号密码登录", description = "用户用手机号或用户名码加密码进行登录")
    @PostMapping("/passWordLogin")
    public ResponseResult<LoginByPhoneAndUserNameAndPasswordRespDTO> loginByPhoneAndUserNameAndPassword(@RequestBody LoginByPhoneAndUserNameAndPasswordReqDTO in) {
        boolean isValid = captchaUtil.validateCaptcha(in.getVKey(), in.getVCode());
        if (!isValid) {
            return ResponseResult.verificationCodeError(null, "验证码错误或已过期");
        }
        return usersService.loginByPhoneAndUserNameAndPassword(in.getPhone(), in.getUserName(), in.getPassword());
    }

    //禁用或启用用户；status=1启用，status=0禁用
    @Operation(summary = "禁用或启用用户", description = "禁用或启用用户；status=1启用，status=0禁用")
    @GetMapping("/disableOrEnableUser")
    public ResponseResult<String> disableUser(@Parameter(description = "用户Id", name = "userId", required = true) @RequestParam(name = "userId") String userId,
                                              @Parameter(description = "状态,status=1启用，status=0禁用", name = "status", required = true) @RequestParam(name = "status") Integer status) {
        return usersService.disableUser(userId, status);
    }

    //获取用户列表
    @Operation(summary = "获取用户列表", description = "获取用户列表")
    @GetMapping("/getUserList")
    public ResponseResult<Page<User>> getUserList(@Parameter(description = "页码", required = true, name = "pageNum") @RequestParam(name = "pageNum") Integer pageNum,
                                                  @Parameter(description = "页大小", required = true, name = "pageSize") @RequestParam(name = "pageSize") Integer pageSize,
                                                  @Parameter(description = "搜索条件", required = false, name = "search") @RequestParam(required = false, name = "search") String search,
                                                  @Parameter(description = "状态,status=1启用，status=0禁用", required = false, name = "status") @RequestParam(name = "status", required = false) Integer status,
                                                  @Parameter(description = "用户类型", required = false, name = "userType") @RequestParam(name = "userType", required = false) Integer userType,
                                                  @Parameter(description = "组织Id", required = false, name = "orgId") @RequestParam(name = "orgId", required = false) String orgId) {
        return usersService.getUserList(pageNum, pageSize, search, status, userType, orgId);
    }

    //根据用户id查询用户信息
    @Operation(summary = "根据用户id查询用户信息", description = "根据用户id查询用户信息")
    @GetMapping("/getUserInfoById")
    public ResponseResult<User> getUserInfoById(@Parameter(description = "用户Id", required = true, name = "userId") @RequestParam(name = "userId") String userId) {
        return ResponseResult.ok(usersService.getUserInfoById(userId));
    }

    //删除用户
    @Operation(summary = "删除用户", description = "删除用户")
    @GetMapping("/deleteUserById")
    public ResponseResult<String> deleteUser(@Parameter(description = "用户Id", required = true, name = "userId") @RequestParam(name = "userId") String userId) {
        return usersService.deleteUser(userId);
    }
}